import 'dart:io';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/demo/ui/screen/demo_ocr_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:camera/camera.dart';
import 'package:casdon/modules/demo/application/notification/demo_camera_notifier.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// 食材扫描拍照
class DemoCameraScreen extends ConsumerStatefulWidget {
  const DemoCameraScreen({super.key});

  @override
  ConsumerState<DemoCameraScreen> createState() => _DemoCameraScreenState();
}

class _DemoCameraScreenState extends ConsumerState<DemoCameraScreen>
    with WidgetsBindingObserver {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    Future.microtask(() async {
      ref.read(cameraControllerProvider.notifier).initCamera();
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    ref.read(cameraControllerProvider.notifier).onLifecycleChanged(state);
  }

  @override
  Widget build(BuildContext context) {
    final cameraState = ref.watch(cameraControllerProvider);

    final controller = ref.watch(cameraControllerProvider).controller;

    if (controller == null || !controller.value.isInitialized) {
      return const Center(child: CircularProgressIndicator());
    }

    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        alignment: Alignment.center,
        children: [
          /// 相机预览
          if (!cameraState.initialized)
            const Center(child: CircularProgressIndicator())
          else
            Positioned.fill(
              child: controller.value.isInitialized
                  ? ClipRect(
                      child: OverflowBox(
                        alignment: Alignment.center,
                        child: FittedBox(
                          fit: BoxFit.cover,
                          child: SizedBox(
                            width: controller.value.previewSize!.height,
                            height: controller.value.previewSize!.width,
                            child: CameraPreview(controller),
                          ),
                        ),
                      ),
                    )
                  : const Center(child: CircularProgressIndicator()),
            ),

          /// 返回按钮
          Positioned(
            left: 8,
            top: 32,
            child: IconButton(
              icon: const Icon(Icons.arrow_back),
              color: Colors.white,
              onPressed: () => Navigator.of(context).maybePop(),
            ),
          ),

          /// 底部操作栏
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: SafeArea(
              child: Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 24.0,
                  vertical: 12.0,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    /// 选择图片
                    ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        shadowColor: Colors.transparent,
                      ),
                      onPressed: () async {
                        final pic = await ref
                            .read(cameraControllerProvider.notifier)
                            .pickImage();
                        _onImageCaptured(pic);
                      },
                      icon: Assets.images.icImagePick.image(
                        width: 50.w,
                        height: 50.w,
                      ),
                      label: SizedBox(),
                    ),

                    /// 拍照按钮（居中大圆形）
                    ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        shadowColor: Colors.transparent,
                      ),
                      onPressed: () async {
                        final pic = await ref
                            .read(cameraControllerProvider.notifier)
                            .takePicture();
                        _onImageCaptured(pic);
                      },
                      icon: Assets.images.icTakePhoto.image(
                        width: 50.w,
                        height: 50.w,
                      ),
                      label: SizedBox(),
                    ),

                    /// 闪光灯开关
                    ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        shadowColor: Colors.transparent,
                      ),
                      onPressed: () => ref
                          .read(cameraControllerProvider.notifier)
                          .toggleTorch(),
                      icon: Assets.images.icLightClose.image(
                        width: 50.w,
                        height: 50.w,
                      ),
                      label: SizedBox(),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> _onImageCaptured(XFile? image) async {
    if (image == null) {
      ToastUtil.show("拍照失败！");
      return;
    }
    if (!context.mounted) return;
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => DemoOcrScreen(imagePath: image.path),
        fullscreenDialog: true,
      ),
    );
  }
}
